﻿/******************************************************************
** auth: wei.huazhong
** date: 8/14/2020 10:35:24
** desc:
******************************************************************/

using System;
using System.Collections.Generic;
using static System.String;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.Extensions.Options;
using Models;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;

namespace Common
{
    public class JwtHelper
    {
        private readonly AppSettings _appSettings;
        private readonly JwtSecurityTokenHandler _jwtTokenHandler;
        private readonly byte[] _secretKey;

        public JwtHelper(IOptions<AppSettings> appSettings)
        {
            _appSettings = appSettings.Value;
            _jwtTokenHandler = new JwtSecurityTokenHandler();
            _secretKey = Encoding.ASCII.GetBytes(_appSettings.Secret);
        }

        public JwtSecurityToken ValidateJwtToken(string token)
        {

            //var tokenHandler = new JwtSecurityTokenHandler();
            //var secretKey = Encoding.ASCII.GetBytes(_appSettings.Secret);

            _jwtTokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(_secretKey), //Symmetric 对称的
                ValidateIssuer = false,//因为不是使用第三方颁发token，所以不认证 issuer？
                ValidateAudience = false,
                // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                ClockSkew = TimeSpan.Zero
            }, out SecurityToken validatedToken); ;

            var jwtToken = (JwtSecurityToken)validatedToken;
            return jwtToken;
        }

        public string GenerateJwtToken(User user)
        {
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] { new Claim("id", user.ID.ToString()), new Claim("name", user.Name) }),
                //Expires = DateTime.Now.AddDays(1),
                Expires = DateTime.Now.AddMinutes(2),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(_secretKey), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = _jwtTokenHandler.CreateToken(tokenDescriptor);
            return _jwtTokenHandler.WriteToken(token);
        }
    }
}
